package com.imooc.bilibili.service;

import com.imooc.bilibili.constant.AuthRoleConstant;
import com.imooc.bilibili.domain.auth.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xiexu
 * @create 2022-06-16 13:31
 */
@Service
public class UserAuthService {

    /**
     * 当前用户绑定了哪些角色
     */
    @Autowired
    private UserRoleService userRoleService;

    /**
     * 这些角色都关联了哪些权限
     */
    @Autowired
    private AuthRoleService authRoleService;

    public UserAuthorities getUserAuthorities(Long userId) {
        // 根据userId来获取用户关联的角色（一个用户可以有多个角色）
        List<UserRole> userRoleList = userRoleService.getUseRoleByUserId(userId);
        // 提取角色id到集合中
        Set<Long> roleIdSet = new HashSet<>();
        for (UserRole userRole : userRoleList) {
            roleIdSet.add(userRole.getRoleId());
        }
        // 将角色id进行批量查询，查询权限
        // 查询按钮操作权限
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationsByRoleIds(roleIdSet);
        // 查询页面菜单访问权限
        List<AuthRoleMenu> authRoleMenuList = authRoleService.getAuthRoleMenusByRoleIds(roleIdSet);
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(authRoleMenuList);

        return userAuthorities;
    }

    /**
     * 给新注册用户添加一个默认权限角色
     *
     * @param id 用户id
     */
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        // 根据默认等级0查询角色信息
        AuthRole role = authRoleService.getRoleByCode(AuthRoleConstant.ROLE_LV0);
        userRole.setUserId(id);
        userRole.setRoleId(role.getId());
        userRoleService.addUserRole(userRole);
    }
}
